#include "DesktopPet.h"
#include <QPainter>
#include <QScreen>
#include <QGuiApplication>
#include <QMouseEvent>
#include <QTransform>
#include <QPushButton>  // 引入按钮类

DesktopPet::DesktopPet(QWidget* parent)
        : QWidget(parent)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool); // 设置无边框、始终在最上层、工具窗口
    setAttribute(Qt::WA_TranslucentBackground); // 设置窗口透明

    // 加载GIF并确保文件路径正确
    movie = new QMovie(":/resource/demo1.gif");
    movie->start();

    // 每当GIF帧更新时，重新绘制窗口
    connect(movie, &QMovie::frameChanged, this, [this](int) {
        update();
    });

    // 获取GIF尺寸
    QSize gifSize = movie->currentPixmap().size();

    // 设置窗口大小，比GIF图像大
    resize(gifSize.width() + padding * 2, gifSize.height() + padding * 2);

    // 创建关闭按钮
    closeButton = new QPushButton("关闭", this);
    closeButton->setGeometry(gifSize.width() - 60, 10, 50, 30); // 设置按钮位置和大小
    connect(closeButton, &QPushButton::clicked, this, &DesktopPet::closePet); // 连接按钮点击事件
}

DesktopPet::~DesktopPet()
{
    if (movie)
        movie->stop(); // 关闭时停止GIF动画
}

void DesktopPet::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    if (movie && movie->isValid())
    {
        // 获取GIF图像，并按窗口尺寸缩放
        QPixmap pix = movie->currentPixmap().scaled(size() - QSize(padding * 2, padding * 2), Qt::KeepAspectRatio, Qt::SmoothTransformation);

        // 计算绘制位置，确保GIF图像居中显示
        int x = (width() - pix.width()) / 2;
        int y = (height() - pix.height()) / 2;

        painter.drawPixmap(x, y, pix); // 绘制GIF图像
    }
}

void DesktopPet::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
    {
        dragPosition = event->globalPos() - frameGeometry().topLeft(); // 记录鼠标按下时的位置
        event->accept();
    }
}

void DesktopPet::mouseMoveEvent(QMouseEvent* event)
{
    if (event->buttons() & Qt::LeftButton) // 如果按下鼠标左键
    {
        move(event->globalPos() - dragPosition); // 更新窗口位置
        event->accept();
    }
}

void DesktopPet::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
    {
        event->accept();
    }
}

// 关闭按钮的槽函数
void DesktopPet::closePet()
{
    close(); // 关闭窗口
}
